package com.oig.sys.auth.service.impl;

import com.oig.common.constants.CommonEnum;
import com.oig.common.exception.BadRequestException;
import com.oig.sys.auth.dao.ITbOpenAuthDao;
import com.oig.sys.auth.service.ITbOpenAuthService;
import com.oig.sys.auth.entity.TbOpenAuth;
import com.oig.sys.auth.dto.OpenAuthDto;
import com.oig.sys.auth.vo.OpenAuthVo;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author wuxl
 */
@Service
public class TbOpenAuthServiceImpl implements ITbOpenAuthService {

	private final ITbOpenAuthDao tbOpenAuthDao;

	@Autowired
	public TbOpenAuthServiceImpl(ITbOpenAuthDao tbOpenAuthDao){
		 this.tbOpenAuthDao = tbOpenAuthDao;
	}

	@Transactional
	@Override
	public OpenAuthVo addOpenAuth(OpenAuthDto openAuthDto){
		TbOpenAuth openAuth = new TbOpenAuth();
		BeanUtils.copyProperties(openAuthDto,openAuth,"id");
		openAuth.setStatus(CommonEnum.CommonStatusEnum.OK.getCode());
		this.tbOpenAuthDao.save(openAuth);
		OpenAuthVo openAuthVo = new OpenAuthVo();
		BeanUtils.copyProperties(openAuth, openAuthVo);
		return openAuthVo;
	}

	@Transactional
	@Override
	public OpenAuthVo updateOpenAuth(OpenAuthDto openAuthDto){
		TbOpenAuth openAuth = this.tbOpenAuthDao.getTbOpenAuthById(openAuthDto.getId());
		if (openAuth==null){
			throw new BadRequestException("记录不存在");
		}
		BeanUtils.copyProperties(openAuthDto,openAuth);
		openAuth.setStatus(CommonEnum.CommonStatusEnum.OK.getCode());
		this.tbOpenAuthDao.save(openAuth);
		OpenAuthVo openAuthVo = new OpenAuthVo();
		BeanUtils.copyProperties(openAuth, openAuthVo);
		return openAuthVo;
	}

	@Transactional
	@Override
	public void cancelOpenAuth(Integer id){
		TbOpenAuth openAuth = this.tbOpenAuthDao.getTbOpenAuthById(id);
		if (openAuth==null){
			throw new BadRequestException("记录不存在");
		}
		openAuth.setStatus(CommonEnum.CommonStatusEnum.DEL.getCode());
		this.tbOpenAuthDao.save(openAuth);
	}


	@Override
	public OpenAuthVo getOpenAuthByType(String type) {
		TbOpenAuth openAuth = this.tbOpenAuthDao.getTbOpenAuthByAuthType(type);
		if (openAuth==null){
			throw new BadRequestException("记录不存在");
		}
		if (!CommonEnum.CommonStatusEnum.OK.getCode().equals(openAuth.getStatus())){
			throw new BadRequestException("登录方式未生效");
		}
		OpenAuthVo openAuthVo = new OpenAuthVo();
		BeanUtils.copyProperties(openAuth, openAuthVo);
		return openAuthVo;
	}

}
